#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define SIZE 1024
#define Sep " "

#define Max_argv 64
int lastcode = 0;

char* argv[Max_argv];



const char * GetUserName()
{ 
  char * userName = getenv("USER");
	if(userName) return userName;
	else return "None";
}

const char* GetHostName()
{
  char *hostname = getenv("HOSTNAME");
  if(hostname) return hostname;
  else return "None";

}


const char *GetPWDName()
{
      char *hostname = getenv("PWD");
      if(hostname) return hostname;
      else return "None";

}
int Interactive(char out[],int size)
{  
   printf("[%s@%s %s]$",GetUserName(),GetHostName(),GetPWDName());
   
   fgets(out,size,stdin);
    out[strlen(out)-1] = '\0';
    return strlen(out);
}


int Split(char in[])
{ 
    int i=0;
    argv[i]=strtok(in,Sep);
    i++;
    while(argv[i++] = strtok(NULL,Sep));

}


void Execute()
{
  pid_t id =fork();
  if(id == 0)
  {
    execvp(argv[0],argv);
  }

  int statue = 0;
  pid_t rid = waitpid(id,&statue,0);
  if(rid == id)
  {
    lastcode=WEXITSTATUS(statue);
  }
}


int main()
{
    while(1)
    {
        char commandline[SIZE];
        // 1. 打印命令行提示符，获取用户输入的命令字符串
        int n = Interactive(commandline, SIZE);
        if(n == 0)
        {
          continue;
        }
    
        // 2. 对命令行字符串进行切割
        Split(commandline);
       
        //执行命令
        Execute();

        //int i=0;
        //for(i=0;argv[i]!=NULL;i++ )
        //{
        //  printf("argv[%d]: %s\n", i,argv[i]);
        //}
        
    }
     return 0;
}
